package com.freeter.modules.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.freeter.modules.gjs.entity.StockStatus;
import com.freeter.modules.gjs.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/app/stocks")
public class StockController {
    @Autowired private StockStatusService stockStatusService;
    @Autowired private TransactionService transactionService;
    @Autowired private DamageReportService damageReportService;
    @Autowired private MstrSiteService mstrSiteService;
    @Autowired private TransferRequestService transferRequestService;

    // 库存现状查询

    @GetMapping("/list")
    public List<StockStatus> listStock() {
        Wrapper<StockStatus> queryWrapper = new EntityWrapper<>();
        return stockStatusService.selectList(queryWrapper);
    }

    // 库存调整

    @PostMapping("/adjustment/submit")
    public ResponseEntity<?> adjustStock(@RequestBody Map<String, Object> req) {
        try {
            transactionService.adjustStock(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 物品出库
//    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/items/mark-usage")
    public ResponseEntity<?> markUsage(@RequestBody Map<String, Object> req) {
        try {
            transactionService.markUsage(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    // 低库存预警
//    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/lowstock")
    public List<StockStatus> lowStockAlert() { return stockStatusService.getLowStockStatus(); }

//    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/item-list")
    public ResponseEntity<?> itemList(@RequestParam Map<String, Object> params) {
        // 参数提取
        String projectCode = (String) params.get("project_code");
        String siteId = (String) params.get("site_id");
        String cat1Id = (String) params.get("cat1_id");
        String cat2Id = (String) params.get("cat2_id");
        String cat3Id = (String) params.get("cat3_id");
        if (projectCode == null || siteId == null || cat1Id == null || cat2Id == null) {
            return ResponseEntity.ok().body(new java.util.ArrayList<>());
        }
        // 拼接cat_id
        String catId = (cat1Id != null ? cat1Id : "") + (cat2Id != null ? cat2Id : "") + (cat3Id != null ? cat3Id : "");
        // 查询view_stock_status
        java.util.List<java.util.Map<String, Object>> result = new java.util.ArrayList<>();
        try {
            result = stockStatusService.itemList(projectCode, siteId, catId);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
        return ResponseEntity.ok().body(result);
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/all-item-list")
    public ResponseEntity<?> allItemList(@RequestParam Map<String, Object> params) {
        try {
            return ResponseEntity.ok().body(stockStatusService.allItemList());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/all-updated-item-list")
    public ResponseEntity<?> allUpdatedItemList(@RequestParam Map<String, Object> params) {
        String projectCode = (String) params.get("project_code");
        String siteId = (String) params.get("site_id");
        String currentLastUpdate = (String) params.get("current_last_update");
        if (projectCode == null || siteId == null || currentLastUpdate == null) {
            return ResponseEntity.ok().body(new java.util.ArrayList<>());
        }
        try {
            return ResponseEntity.ok().body(stockStatusService.allUpdatedItemList(projectCode, siteId, currentLastUpdate));
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/item")
    public ResponseEntity<?> item(@RequestParam Map<String, Object> params) {
        String projectCode = (String) params.get("project_code");
        String siteId = (String) params.get("site_id");
        String id = (String) params.get("id");
        String itemBarcode = (String) params.get("item_barcode");
        if (projectCode == null || siteId == null || (id == null && itemBarcode == null)) {
            return ResponseEntity.status(404).body("Item not found");
        }
        try {
            Map<String, Object> result = stockStatusService.item(projectCode, siteId, id, itemBarcode);
            if (result == null) {
                return ResponseEntity.status(404).body("Item not found");
            }
            return ResponseEntity.ok().body(result);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/mark-usage-background-run")
    public ResponseEntity<?> markUsageBackgroundRun(@RequestBody Map<String, Object> req) {
        try {
            transactionService.markUsage(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/report-demage")
    public ResponseEntity<?> reportDemage(@RequestBody Map<String, Object> req) {
        try {
            damageReportService.reportDemage(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/report-demage-background-run")
    public ResponseEntity<?> reportDemageBackgroundRun(@RequestBody Map<String, Object> req) {
        try {
            damageReportService.reportDemage(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/reloc-to-sites")
    public ResponseEntity<?> relocToSites(@RequestParam Map<String, Object> params) {
        try {
            return ResponseEntity.ok().body(mstrSiteService.getAllActiveSites());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/reloc-request")
    public ResponseEntity<?> relocRequest(@RequestBody Map<String, Object> req) {
        try {
            transferRequestService.relocRequest(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/reloc-pending-count")
    public ResponseEntity<?> relocPendingCount(@RequestParam Map<String, Object> params) {
        try {
            int count = transferRequestService.getRelocPendingCount(params);
            return ResponseEntity.ok().body(count);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/reloc-pending")
    public ResponseEntity<?> relocPending(@RequestParam Map<String, Object> params) {
        try {
            List<Map<String, Object>> list = transferRequestService.getRelocPendingList(params);
            return ResponseEntity.ok().body(list);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/reloc-pending-cancel")
    public ResponseEntity<?> relocPendingCancel(@RequestBody Map<String, Object> req) {
        try {
            transferRequestService.cancelRelocPending(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/reloc-approve")
    public ResponseEntity<?> relocApprove(@RequestBody Map<String, Object> req) {
        try {
            transferRequestService.approveRelocRequest(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/reloc-non-rec-count")
    public ResponseEntity<?> relocNonRecCount(@RequestParam Map<String, Object> params) {
        try {
            int count = transferRequestService.getRelocNonRecCount(params);
            return ResponseEntity.ok().body(count);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @GetMapping("/reloc-non-rec")
    public ResponseEntity<?> relocNonRec(@RequestParam Map<String, Object> params) {
        try {
            List<Map<String, Object>> list = transferRequestService.getRelocNonRecList(params);
            return ResponseEntity.ok().body(list);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("An unexpected error occurred");
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/reloc-receive")
    public ResponseEntity<?> relocReceive(@RequestBody Map<String, Object> req) {
        try {
            transferRequestService.relocReceive(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    //@PreAuthorize("isAuthenticated()")
    @PostMapping("/reloc-receive-background-run")
    public ResponseEntity<?> relocReceiveBackgroundRun(@RequestBody Map<String, Object> req) {
        try {
            transferRequestService.relocReceive(req);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
}